<?php

namespace app\api\controller\user;

use think\Controller;


class Address extends Controller{

    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');

        $this->AddressModel = model('User.Address');

        $this->RegionModel = model('Region');
    }

    // 收货地址列表
    public function index()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', '');

            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo)
            {
                $this->error('用户不存在');
                exit;
            }

            $result = $this->AddressModel->with(['provinces','citys','districts'])->where(['userid' => $userid])->select();

            $this->success('返回收货地址成功', null, $result);
            exit;
        }
    }

    // 添加
    public function add()
    {
        
        if($this->request->isPost())
        {
            $params = $this->request->param();

            $userinfo = $this->UserModel->find($params['userid']);

            if(!$userinfo)
            {
                $this->error('用户不存在');
                exit;
            }

            //组装数据
            $data = [
                'consignee' => $params['consignee'],
                'mobile' => $params['mobile'],
                'address' => $params['address'],
                'status' => $params['status'],
                'userid' => $params['userid'],
            ];

            //查询地区数据
            $parentpath = $this->RegionModel->where(['code' => $params['code']])->value('parentpath');

            if(empty($parentpath)){
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将字符串转换为数组
            $path = explode(',', $parentpath);

            if(count($path) <= 0)
            {
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将数组里面的值分别给到不同的变量
            list($data['province'], $data['city'], $data['district']) = $path;

            //判断是否选择了默认地址
            if($params['status'] == 1){
                //将这个人所有的收货地址都要改成非默认
                $UpdateStatus = $this->AddressModel->where(['userid' => $params['userid']])->update(['status' => 0]);

                if($UpdateStatus === FALSE)
                {
                    $this->error('更新默认收货地址失败');
                    exit;
                }
            }

            //插入数据库
            $result = $this->AddressModel->validate('common/User/Address')->save($data);

            if($result === FALSE)
            {
                $this->error($this->AddressModel->getError());
                exit;
            }else
            {
                $this->success('添加收货地址成功');
                exit;
            }
        }
    }

    // 切换默念地址
    public function check()
    {
        if($this->request->isPost())
        {
            $id = $this->request->param('id', 0 );
            $userid = $this->request->param('userid', 0);

            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo)
            {
                $this->error('用户不存在');
                exit;
            }

            $addressinfo = $this->AddressModel->find($id);

            if(!$addressinfo)
            {
                $this->error('收货地址不存在');
                exit;
            }

            if($userid != $addressinfo['userid']){

                $this->error('非法修改他人地址，无权修改');
                exit;
            }

            //先把这个人的所有的收货地址都改成0 非默认 ，在改指定这个id地址

            //开启事务
            $this->AddressModel->startTrans();

            $UpdateStatus = $this->AddressModel->where(['userid' => $userid])->update(['status' => 0]);

            if($UpdateStatus === FALSE)
            {
                $this->error('更新默认收货地址失败');
                exit;
            }

            //更新选中的地址
            $result = $this->AddressModel->where(['id' => $id])->update(['status' => 1]);

            if($result === FALSE)
            {
                //回滚事务
                $this->AddressModel->rollback();
                $this->error('更新默认地址失败');
                exit;
            }else
            {
                //提交事务
                $this->AddressModel->commit();
                $this->success('更新默认地址成功');
                exit;
            }
        } 
    }

    // 详情
    public function info()
    {
        if($this->request->isPost())
        {
            $id = $this->request->param('id', 0 );
            $userid = $this->request->param('userid', 0);

            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo)
            {
                $this->error('用户不存在');
                exit;
            }

            $addressinfo = $this->AddressModel->with(['provinces','citys','districts'])->find($id);

            if($addressinfo === FALSE)
            {
                $this->error($this->AddressModel->getError());
                exit;
            }else
            {
                $this->success('', null, $addressinfo);
                exit;
            }
        }
    }

    // 编辑
    public function edit()
    {
        if($this->request->isPost())
        {
            $params = $this->request->param();
            $id = $this->request->param('id', 0);

            $userinfo = $this->UserModel->find($params['userid']);

            if(!$userinfo)
            {
                $this->error('用户不存在');
                exit;
            }

            //组装数据
            $data = [
                'id' => $id,
                'consignee' => $params['consignee'],
                'mobile' => $params['mobile'],
                'address' => $params['address'],
                'status' => $params['status'],
                'userid' => $params['userid'],
            ];

            //查询地区数据
            $parentpath = $this->RegionModel->where(['code' => $params['code']])->value('parentpath');

            if(empty($parentpath)){
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将字符串转换为数组
            $path = explode(',', $parentpath);

            if(count($path) <= 0)
            {
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将数组里面的值分别给到不同的变量
            list($data['province'], $data['city'], $data['district']) = $path;

            //判断是否选择了默认地址
            if($params['status'] == 1){
                //将这个人所有的收货地址都要改成非默认
                $UpdateStatus = $this->AddressModel->where(['userid' => $params['userid']])->update(['status' => 0]);

                if($UpdateStatus === FALSE)
                {
                    $this->error('更新收货地址失败');
                    exit;
                }
            }
            //更新数据库
            $result = $this->AddressModel->validate('common/User/Address')->isUpdate()->save($data);
            if($result === FALSE)
            {
                $this->error($this->AddressModel->getError());
                exit;
            }else
            {
                $this->success('修改收货地址成功');
                exit;
            }
            
        }
    }

    // 删除
    public function del(){
        
        if($this->request->isPost())
        {
            $id = $this->request->param('id', 0 );
            $userid = $this->request->param('userid', 0);
            $status = $this->request->param('status', 0);

            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo)
            {
                $this->error('用户不存在');
                exit;
            }

            $addressinfo = $this->AddressModel->find($id);

            if(!$addressinfo)
            {
                $this->error('收货地址不存在');
                exit;
            }

            $result = $this->AddressModel->destroy($id);
            
            if($result === FALSE)
            {
                $this->error($this->AddressModel->getError());
                exit;
            }else
            {
                $this->success('删除成功');
                exit;
            }
        }
    }

    //订单默认地址
    public function order()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', '');

            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo)
            {
                $this->error('用户不存在');
                exit;
            }

            $data = [
                'userid' => $userid,
                'status' =>1
            ];

            //查找这个人的默认收货地址
            $info = $this->AddressModel->with(['provinces','citys','districts'])->where($data)->find();

            if($info)
            {
                $this->success('返回默认收货地址', null, $info);
                exit;
            }

            //如果没有默认的收货地址，就随便找一条给他
            $address = $this->AddressModel->with(['provinces','citys','districts'])->where(['userid' => $userid])->find();

            if(!$address)
            {
                $this->error('暂无收货地址');
                exit;
            }

            $this->success('返回默认收货地址', null, $address);
            exit;
        }
    }
}